package com.github.llyb120.szuniver.document.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.github.llyb120.json.Arr;
import com.github.llyb120.json.Obj;
import com.github.llyb120.json.TypeReference;
import com.github.llyb120.szuniver.document.entity.User;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.ReplaceOptions;
import org.bson.Document;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.github.llyb120.json.Json.*;

/**
 * @Author: Administrator
 * @Date: 2020/9/24 18:18
 */
@Service
public class UserService {

    @Resource
    MongoDatabase db;

    public static final String COL_USER = "t_user";


    public boolean saveUser(User user){
        if(StrUtil.isBlank(user.getId())){
            user.setId(IdUtil.objectId());
        }
        int d = 4;
        Arr arr2 = a(1,2,3);
        Object arr = a(
            1,
            2,
            3,
            $expand, arr2,
            arr2.yield(e -> ((int)e) + 1)
        ).or(
            1
        );
//        if(true){
//            arr.add(1);
//        }
        Obj obj = o(
            "test", 1,
            "fuck", 2,
            "test2", o(

            ),
            "test3", a(
                o(

                )
            )
        );
        Obj item1 = o(
            "a", 1,
            "b", 2
        );
        Obj item2 = o(
            item1,
            "c", 2
        );
        Map map = new HashMap<>();
        map.putAll(item1);
        map.put("c", 2);
        /**
         * var item1 = {a:1,b:2}
         * var item2 = {
         *  ...item1,
         *  c: 2
         * }
         *
         *
         *
         */


        /**
         *
         * []
         *
         * {
         * test:1,
         * fuck:2
         * }
         */
//        o(),
//            a()
//        if(StrUtil.isBlank(user.getName())){
//
//        }

        db.getCollection(COL_USER)
           .replaceOne(
               bo("id", user.getId()),
               bo(user),
                new ReplaceOptions().upsert(true)
           );

        return true;
    }


    public List<User> search(String name){
        Arr<Document> items = db.getCollection(COL_USER)
            .find(bo(
                "name", o(
                    "$regex", name
                )
            ))
            .into(a());

        return cast(items, new TypeReference<List<User>>(){});
    }


    public User findOne(final String id){
        Document doc = db.getCollection(COL_USER)
            .find(bo("id", id))
            .first();
        if (doc == null) {
            //throw
        }
        return cast(doc, User.class);
    }
}
